package com.loopy.fruns.filter;

import com.loopy.fruns.entity.Member;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 权限验证的过滤器
 */
public class AuthFilter implements Filter {
    private List<String> excludedUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("====ManageFilter init()被调用..====");
        String strExcludedUrls = filterConfig.getInitParameter("excludedUrls");
        String[] split = strExcludedUrls.split(",");
        excludedUrls = Arrays.asList(split);
        System.out.println("excludedUrls="+excludedUrls);
//        if()
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        System.out.println("=====ManageFilter doFilter()被调用====");

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestURL = httpServletRequest.getServletPath();
        System.out.println("请求的url=" + requestURL);
        HttpSession session = httpServletRequest.getSession();

        if (!excludedUrls.contains(requestURL)) {
            Member member = (Member) session.getAttribute("member");
            if (null == member) {
                servletRequest.getRequestDispatcher("/views/member/login.jsp").forward(servletRequest, servletResponse);
                return;
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);


    }

    @Override
    public void destroy() {
        System.out.println("====ManageFilter destroy()被调用..====");
    }
}
